import pinia from '../store'
import { HOME, HOME_PATH } from '../constant'
import { useUserStore } from '../store/user'
import { checkLoginState } from '../requests/login'
import { createRouter, createWebHashHistory, RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { useRouterStore } from '@/framework/store/router'
import { useRefreshStore } from '@/framework/store/layout/refresh'

const NotFound = () => import('../views/NotFound/index.vue')
const Home = () => import('../views/Home/index.vue')

export const staticRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: HOME_PATH
  },
  {
    path: HOME_PATH,
    name: HOME,
    component: Home
  },
  {
    path: '/:catchAll(.*)',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRoutes]
})

export const clearQueryParams = () => {
  router.replace({
    ...router.currentRoute.value,
    query: {}
  })
}

const commonStore = useUserStore(pinia)
const routeStore = useRouterStore(pinia)
const refreshStore = useRefreshStore(pinia)

let externalRouterGuardHandler = (to: RouteLocationNormalized, from: RouteLocationNormalized): void => {}

export const setExternalRouterGuard = (
  externalRouterGuard: (to: RouteLocationNormalized, from: RouteLocationNormalized) => void
) => {
  externalRouterGuardHandler = externalRouterGuard
}

export const routerGuard = async (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  if (routeStore.getLastRoute.fullPath === to.fullPath && routeStore.isBlockReturn) {
    routeStore.blockReturnHandler()
    return false
  } else {
    routeStore.setLastRoute(from)
    routeStore.setCurrentRoute(to)
    refreshStore.clearRefresh()
    // 未登录
    if (!commonStore.hasLogin) {
      await checkLoginState()
      delete to.query.id_token
      return true
    } else {
      externalRouterGuardHandler(to, from)
      return true
    }
  }
}
router.beforeEach(routerGuard)

export default router
